<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog" @click.stop>
      <div class="apple-card__header">
        <h2 class="text-heading">编辑角色</h2>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <form class="apple-card__body" @submit.prevent="handleSubmit">
        <div class="form-group">
          <label class="form-label">角色名称 *</label>
          <input
            v-model="form.name"
            class="apple-input"
            :class="{ 'apple-input--error': errors.name }"
            placeholder="请输入角色名称"
            maxlength="50"
            required
          >
          <div v-if="errors.name" class="error-message">{{ errors.name }}</div>
        </div>

        <div class="form-group">
          <label class="form-label">角色编码</label>
          <input
            :value="role?.code"
            class="apple-input disabled-input"
            disabled
            readonly
          >
          <div class="form-help">角色编码创建后不可修改</div>
        </div>

        <div class="form-group">
          <label class="form-label">角色描述</label>
          <textarea
            v-model="form.description"
            class="apple-input textarea"
            placeholder="请输入角色描述"
            rows="3"
            maxlength="200"
          ></textarea>
          <div class="char-count">{{ form.description.length }}/200</div>
        </div>

        <div class="form-group">
          <label class="switch-label">
            <div class="switch-info">
              <span class="form-label">角色状态</span>
              <span class="form-help">禁用后用户将无法使用此角色的权限</span>
            </div>
            <div 
              class="apple-switch"
              :class="{ 'apple-switch--active': form.is_active }"
              @click="form.is_active = !form.is_active"
            ></div>
          </label>
        </div>

        <!-- 系统角色警告 -->
        <div v-if="role?.is_system" class="system-role-warning">
          <div class="warning-icon">⚠️</div>
          <div class="warning-content">
            <h4 class="text-body">系统角色</h4>
            <p class="text-caption">此角色为系统内置角色，某些修改可能受到限制</p>
          </div>
        </div>
      </form>

      <div class="apple-card__footer">
        <button 
          type="button"
          class="apple-button apple-button--secondary"
          @click="handleClose"
        >
          取消
        </button>
        <button 
          type="submit"
          class="apple-button apple-button--primary"
          :disabled="!isFormValid || submitting || !hasChanges"
          @click="handleSubmit"
        >
          {{ submitting ? '保存中...' : '保存更改' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { roleApi } from '@/api/rbac'
import type { Role } from '@/types/rbac'

// Props
interface Props {
  modelValue: boolean
  role: Role | null
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'updated'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单数据
const form = ref({
  name: '',
  description: '',
  is_active: true
})

// 原始数据（用于检测变化）
const originalData = ref({
  name: '',
  description: '',
  is_active: true
})

// 表单验证错误
const errors = ref({
  name: ''
})

// 状态
const submitting = ref(false)

// 计算属性
const isFormValid = computed(() => {
  return form.value.name.trim() && !errors.value.name
})

const hasChanges = computed(() => {
  return form.value.name !== originalData.value.name ||
         form.value.description !== originalData.value.description ||
         form.value.is_active !== originalData.value.is_active
})

// 验证函数
const validateName = () => {
  if (!form.value.name.trim()) {
    errors.value.name = '角色名称不能为空'
  } else if (form.value.name.length > 50) {
    errors.value.name = '角色名称不能超过50个字符'
  } else {
    errors.value.name = ''
  }
}

// 初始化表单数据
const initializeForm = () => {
  if (props.role) {
    const data = {
      name: props.role.name,
      description: props.role.description || '',
      is_active: props.role.is_active
    }
    
    form.value = { ...data }
    originalData.value = { ...data }
    
    // 清除错误
    errors.value.name = ''
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 点击遮罩关闭
const handleOverlayClick = () => {
  handleClose()
}

// 提交表单
const handleSubmit = async () => {
  if (!props.role) return
  
  validateName()
  
  if (!isFormValid.value || !hasChanges.value) {
    return
  }
  
  submitting.value = true
  
  try {
    const updateData: any = {}
    
    if (form.value.name !== originalData.value.name) {
      updateData.name = form.value.name.trim()
    }
    
    if (form.value.description !== originalData.value.description) {
      updateData.description = form.value.description.trim() || null
    }
    
    if (form.value.is_active !== originalData.value.is_active) {
      updateData.is_active = form.value.is_active
    }
    
    const response = await roleApi.updateRole(props.role.id, updateData)
    
    if (response.success) {
      emit('updated')
      handleClose()
      ElMessage.success('角色更新成功')
    }
  } catch (error: any) {
    console.error('更新角色失败:', error)
    if (error.response?.data?.detail?.includes('系统角色不允许修改')) {
      ElMessage.error('系统角色不允许修改')
    } else {
      ElMessage.error('更新角色失败')
    }
  } finally {
    submitting.value = false
  }
}

// 监听表单变化
watch(() => form.value.name, validateName)

// 监听对话框打开和角色变化
watch([() => props.modelValue, () => props.role], ([newValue, newRole]) => {
  if (newValue && newRole) {
    initializeForm()
  }
}, { immediate: true })
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.modal-dialog {
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-button {
  position: absolute;
  right: 0;
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-xs);
  font-weight: 500;
  color: var(--text-primary);
}

.form-help {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--text-tertiary);
}

.error-message {
  margin-top: var(--spacing-xs);
  font-size: 12px;
  color: var(--color-danger);
}

.char-count {
  margin-top: var(--spacing-xs);
  font-size: 11px;
  color: var(--text-tertiary);
  text-align: right;
}

.textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.disabled-input {
  background-color: var(--bg-tertiary);
  color: var(--text-tertiary);
  cursor: not-allowed;
}

.switch-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: var(--spacing-sm) 0;
}

.switch-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.switch-info .form-label {
  margin-bottom: 0;
}

.system-role-warning {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background-color: rgba(255, 149, 0, 0.1);
  border-left: 4px solid var(--color-warning);
  border-radius: var(--radius-medium);
  margin-bottom: var(--spacing-md);
}

.warning-icon {
  font-size: 20px;
  margin-top: 2px;
}

.warning-content h4 {
  margin: 0 0 var(--spacing-xs) 0;
  color: var(--color-warning);
}

.warning-content p {
  margin: 0;
}

.apple-card__footer {
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .modal-dialog {
    max-height: 95vh;
  }
  
  .apple-card__footer {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .apple-card__footer .apple-button {
    width: 100%;
  }
}
</style>